package tjs.study.notes.dotest.io.nio;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by Nicky.Tang on 2021/11/2 4:28 下午
 *
 * @since 02.12.10
 */
public class DoTestOfClient {
    static ExecutorService executorService = Executors.newSingleThreadExecutor();

    public static void main(String[] args) throws Exception {
        // 打开一个通道
        SocketChannel clientChannel = SocketChannel.open();
        // 开启非阻塞模式(阻塞模式就不是这种写法了，Selector必须要在非阻塞模式下运行，否则会报错)
        clientChannel.configureBlocking(false);

        // 开启选择器
        Selector selector = Selector.open();

        // 注册感兴趣的事件
        clientChannel.register(selector, SelectionKey.OP_CONNECT | SelectionKey.OP_READ);

        // 连接到服务端
        clientChannel.connect(new InetSocketAddress(DoTestOfServer.host, DoTestOfServer.port));
        while (selector.select() > 0) {//select会阻塞，直到至少一个事件就绪
            // 获取本次select轮询时的结果 -> 已就绪的事件集合
            Iterator<SelectionKey> selectionIterator = selector.selectedKeys().iterator();
            while (selectionIterator.hasNext()) {
                try {
                    SelectionKey curSelection = selectionIterator.next();
                    SocketChannel curChannel = (SocketChannel) curSelection.channel();

                    if (curSelection.isConnectable()) {// 非阻塞模式下，该方法会立即返回，可能未完全连接成功也会返回true
                        if (curChannel.finishConnect()) {// 再次判断是否已经完全连接好，此方法会阻塞
                            System.out.println("已成功连接到服务器......");
                            curChannel.register(selector, SelectionKey.OP_READ);
                            writeData(curChannel);
                        }
                    } else if (curSelection.isReadable()) {
                        // 开始读取数据（此处有很多坑，半包问题等）
                        DoTestOfServer.redaData(curSelection, curChannel);
                    }
                } finally {
                    // 从选择器中移除当前Selection，否则下次轮询依然是已就绪的状态
                    selectionIterator.remove();
                }
            }
        }
    }

    private static void writeData(SocketChannel curChannel) {
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        executorService.submit(() -> {
            while (true) {
                try {
                    buffer.clear();

                    InputStreamReader input = new InputStreamReader(System.in);
                    BufferedReader br = new BufferedReader(input);
                    String msg = br.readLine();
                    buffer.put(msg.getBytes());
                    buffer.flip();
                    curChannel.write(buffer);

                    System.out.println("请输入消息：");
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        });
    }
}
